/*
 * G2OClientConnect.cpp
 *
 *  Created on: Sep 8, 2016
 *      Author: ubuntu
 */

#include "G2OClientConnect.h"
#include "../common.h"
#include "../Conf.h"
#include "G2OParse.h"
#include "G2ODataInfo.h"
#include <pthread.h>
#include <errno.h>
#include "../DBManager.h"

static const char rand_code[] = {
	'0', '1', '2', '3', '4', '5', '6', '7', 
	'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};

G2OClientConnection::G2OClientConnection(TcpServer *parent, struct connectop *op, struct sockaddr *addr) :
	ClientConnection(parent, op, addr)
{
	memset(m_obdid, 0, sizeof(m_obdid));
	memset(m_key, 0, sizeof(m_key));
	srand(tm_conn);
	for (int i = 0; i < 32; i++)
		m_key[i] = rand_code[rand() % 16];
	debug(LOG_DEBUG, "A new client, and key: [%s]", m_key);
	add_head = ADD_HEAD + 12;
	add_len = add_head + add_tail;
}

G2OClientConnection::~G2OClientConnection()
{
	debug(LOG_DEBUG, "Client delete");
}

bool G2OClientConnection::parsePackage(unsigned char *kBuf, size_t len, int add_head, int add_tail)
{
	G2ODataInfo *pDataInfo = new G2ODataInfo();
	if (!pDataInfo->parse(kBuf, len, add_head, add_tail)) {
		delete pDataInfo;
		return false;
	}

	pDataInfo->set_obdid(m_obdid, sizeof(m_obdid));
	recv_data_output(kBuf+add_head, len);

	unsigned char resBuf[1024];
	int k = 0;
	if ((k = pDataInfo->sendBuf(resBuf, sizeof(resBuf), m_key)) > 0)
		sendBuf(resBuf, k);

	pDataInfo->debugInfo();

	pushDataInfo(pDataInfo);

	return true;
}

void G2OClientConnection::recv_data_output(unsigned char *buf, size_t len)
{
	if (strlen(m_obdid) == 0) {
		ClientConnection::recv_data_output(buf, len);
		return;
	}

	char *tmp = (char *)malloc(len * 2 + 1);
	if (tmp) {
		for (size_t i = 0; i < len; i++)
			sprintf(tmp+i*2, "%02X", buf[i]);
		debug(LOG_DEBUG, "设备%s消息: [%s]", m_obdid, tmp);
		free(tmp);
	}
}
